package com.yupi.springbootinit.manager;

import com.github.rholder.retry.*;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.utils.InvalidEchartsUtil;
import com.yupi.yucongming.dev.client.YuCongMingClient;
import com.yupi.yucongming.dev.common.BaseResponse;
import com.yupi.yucongming.dev.model.DevChatRequest;
import com.yupi.yucongming.dev.model.DevChatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class AiManager {
    @Resource
    private YuCongMingClient client;
    private final Retryer<String> retryer = RetryerBuilder.<String>newBuilder()
            .retryIfResult(result->(!checkEchartsCode(result)))
            .withStopStrategy(StopStrategies.stopAfterAttempt(2))
            .withWaitStrategy(WaitStrategies.fixedWait(2, TimeUnit.SECONDS))
            .build();
    public String doChat(long biModelId,String message){
        DevChatRequest devChatRequest = new DevChatRequest();
        devChatRequest.setModelId(biModelId);
        devChatRequest.setMessage(message);
        client.doChat(devChatRequest);
        BaseResponse<DevChatResponse> response = client.doChat(devChatRequest);
        if (response==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"ai未响应");
        }
        return response.getData().getContent();
    }
    public String doChatWithRetry(String userPrompt) throws Exception {
        log.info("AI代码有误：开始执行重试");
        try {
            Callable<String> callable = () -> {
                // 在这里调用你的doChat方法
                return doChat(CommonConstant.BI_MODEL_ID, userPrompt);
            };
            return retryer.call(callable);
        } catch (RetryException e) {
            throw new Exception("重试失败", e);
        }
    }

    public boolean checkEchartsCode(String answer){
        log.info("正在检查代码是否有误");
        String[] split = answer.split("【【【【【");
        if (split.length < 3) {
            return false;
        }
        String genChart = split[1].trim();//trim去掉多余的空格换行
        boolean isValid = InvalidEchartsUtil.checkEchartsTest(genChart);
        return isValid;
    }
}
